package apkinser

import (
    "os"
    "io"
    "log"
    "time"
    "net"
    "net/http"
    "io/ioutil"
)

// 1min time out
var timeout = time.Duration(60 * time.Second)

func dialTimeout(network, addr string) (net.Conn, error) {
    return net.DialTimeout(network, addr, timeout)
}

func FetchApk(url, savepath string) error {
    _, err := Download(url, savepath)
    return err
}


func Get(url string) ([]byte, error) {
    transport := http.Transport{
        Dial: dialTimeout,
    }

    client := http.Client{
        Transport: &transport,
    }

    resp, err := client.Get(url)

    if err != nil {
        log.Println(err)
        return nil, err
    }

    body, err := ioutil.ReadAll(resp.Body)
    log.Printf("%d", resp.StatusCode)
    resp.Body.Close()

    return body, err
}

func Download(url string, path string) (int64, error) {
    transport := http.Transport{
        Dial: dialTimeout,
    }

    client := http.Client{
        Transport: &transport,
    }

    resp, err := client.Get(url)
    defer resp.Body.Close()

    if err != nil {
        log.Println(err)
        return 0, err
    }

    log.Printf("%d", resp.StatusCode)

    out, err := os.Create(path)
    if err != nil {
        log.Println(err)
        return 0, err
    }

    defer out.Close()

    n, err := io.Copy(out, resp.Body)
    if err != nil {
        log.Println(err)
        return 0, err
    }

    return n, nil
}
